package com.tc.biz.service.impl;

import com.tc.biz.entity.DrainagePipeMaintainence;
import com.tc.biz.mapper.DrainagePipeMaintainenceMapper;
import com.tc.biz.service.IDrainagePipeMainService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * @author zengqingfa
 * @date 2019/11/4 16:35
 * @description
 * @email zengqingfa_java@163.com
 */
@Service
@Transactional
public class DrainagePipeMainServiceImpl implements IDrainagePipeMainService {

    protected static final Logger logger = LoggerFactory.getLogger(DrainagePipeMainServiceImpl.class);

    @Autowired
    private DrainagePipeMaintainenceMapper mapper;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Override
    public int deleteByPrimaryKey(String id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(DrainagePipeMaintainence record) {
        return mapper.insert(record);
    }

    @Override
    public int insertSelective(DrainagePipeMaintainence record) {
        return mapper.insertSelective(record);
    }

    @Override
    public DrainagePipeMaintainence selectByPrimaryKey(String id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(DrainagePipeMaintainence record) {
        return mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(DrainagePipeMaintainence record) {
        return mapper.updateByPrimaryKey(record);
    }

    @Override
    public ProcessInstance start(DrainagePipeMaintainence drainagePipeMaintainence, Map<String, Object> variables, String userId, String processDefinitionId) {
        //保存业务数据
        mapper.insert(drainagePipeMaintainence);
        String businessKey = drainagePipeMaintainence.getId();
        ProcessInstance processInstance = null;
        try {
            ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
            ProcessDefinition processDefinition = processDefinitionQuery.processDefinitionId(processDefinitionId).singleResult();
            // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
            identityService.setAuthenticatedUserId(userId);
            processInstance = runtimeService.startProcessInstanceByKey(processDefinition.getKey(), businessKey, variables);
            logger.debug("start a processinstance: {}", processInstance);
            String processInstanceId = processInstance.getId();
            drainagePipeMaintainence.setProcessInstanceId(processInstanceId);
            drainagePipeMaintainence.setProcessDefId(processInstance.getProcessDefinitionId());
            //根据主键更新到数据表
            mapper.updateByPrimaryKey(drainagePipeMaintainence);
            logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{"pipeMaintainence", businessKey, processInstanceId, variables});
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
        return processInstance;
    }

    @Override
    public DrainagePipeMaintainence findByProcessInstanceId(String processInstanceId) {
        return mapper.findByProcessInstanceId(processInstanceId);
    }

    /**
     * 查询某个流程实例是由哪个用户发起的
     *
     * @param taskId
     * @return
     */
    public String getStartedBy(String taskId) {
        HistoricTaskInstanceQuery historicTaskInstanceQuery = historyService.createHistoricTaskInstanceQuery();
        HistoricTaskInstance historicTaskInstance = historicTaskInstanceQuery.taskId(taskId).singleResult();
        String processInstanceId = historicTaskInstance.getProcessInstanceId();
        return getStartedByProcessInstanceId(processInstanceId);
    }


    /**
     * 查询某个流程实例是由哪个用户发起的
     * @param processInstanceId
     * @return
     */
    public String getStartedByProcessInstanceId(String processInstanceId) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return historicProcessInstance.getStartUserId();
    }
}
